import { create } from 'zustand';
import { UserApi } from '@/api/user/api.js';
import ModalUtil from '@/utils/modal.js';
import { useTabsStore } from '@/store/index.js';
import { persist } from 'zustand/middleware';
import TokenUtil from '@/utils/token.js';
import { cancelRequest, getRequestId } from '@/utils/request.js';

const requestIdByGetUser = getRequestId();
const useUserStore = create(
  persist(
    (set, get) => ({
      // 是否已经登录
      isLogin: false,
      // Token
      token: '',
      // 用户信息
      user: {},
      // 设置token
      setToken: (token) => {
        // 缓存token到cookie中
        TokenUtil.setToken(token);
        // 设置token和登录状态
        set({ token, isLogin: true });
      },
      // 用户登录
      login: async (username, password) => {
        const { code, data } = await UserApi.login({
          username,
          password
        });
        if (code === 0) {
          const token = data.token;
          if (token) {
            // 设置token
            get().setToken(token);
            // 获取用户信息
            await get().getUser();
            ModalUtil.success('登录成功');
          }
        }
      },
      // 获取用户信息
      getUser: async () => {
        cancelRequest(requestIdByGetUser);
        const { code, data } = await UserApi.getLoginUser(requestIdByGetUser);
        if (code === 0) {
          set({
            user: data
          });
        }
      },
      // 退出登录
      logout: async () => {
        const { code } = await UserApi.logout();
        if (code === 0) {
          // 清空信息
          get().clear();
          // 清空标签页
          useTabsStore.getState().clear();
          // 提示
          ModalUtil.success('退出成功');
        }
      },
      // 清空信息
      clear: () => {
        // 删除cookie中的token
        TokenUtil.removeToken();
        // 清空状态
        set({ isLogin: false, token: '', user: {} });
      }
    }),
    {
      name: 'user-storage'
    }
  )
);

export default useUserStore;
